<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Cache;

use App\Cache\Repository\StringRedis;
use App\Model\Group;

class GroupCache extends StringRedis
{
    protected $name = 'group-cache';

    /**
     * 更新缓存.
     */
    public function updateCache(int $group_id): array
    {
        $group = Group::where('id', $group_id)->first();

        if (! $group) {
            return [];
        }

        $group = $group->toArray();

        $this->set(strval($group_id), json_encode($group), 60 * 60 * 1);

        return $group;
    }

    /**
     * 获取或更新群组缓存.
     *
     * @param int $group_id 群组ID
     */
    public function getOrSetCache(int $group_id): array
    {
        $cache = $this->get(strval($group_id));
        return $cache ? json_decode($cache, true) : $this->updateCache($group_id);
    }
}
